<?php

namespace app\admin\controller;

use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use app\common\model\Admin;
use app\common\model\Custom as ModelCustom;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;
use Jdy;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 * 客户管理
 *
 * @icon fa fa-circle-o
 */
class Custom extends Backend
{

    /**
     * Custom模型对象
     * @var \app\common\model\Custom
     */
    protected $model = null;
    protected $acctLimit = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Custom;
        $uids = AuthGroupAccess::where('group_id', 10)->column('uid');
        $adminlist = Admin::whereIn('id', $uids)->column('acct_id,nickname');
        $this->assignconfig("adminlist", $adminlist);
        $this->selectpageFields = ['id', 'name', 'phone'];
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user'])
                // ->where('custom.is_pool', 0)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('user')->visible(['nickname', 'mobile']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $has = ModelCustom::where('phone', $params['phone'])->where('id', '<>', $ids)->find();
            if ($has) {
                exception('该客户已存在');
            }
            $params['province_id'] = $params['province'];
            $params['city_id'] = $params['city'];
            $params['area_id'] = $params['area'];
            $params['city'] = db('cnarea')->where('area_code', $params['province'])->value('name') . '/' . db('cnarea')->where('area_code', $params['city'])->value('name') . '/' . db('cnarea')->where('area_code', $params['area'])->value('name');
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 导入
     */
    public function import($ids = null)
    {
        // $pg = $this->model->get($ids);
        // $this->view->assign("row", $pg);
        // $row = 
        set_time_limit(0);
        if ($this->request->isPost()) {
            $msg = '';

            $file = $this->request->request('idata');
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }



            $fieldArr = [
                'Id' => 'id',
                // '好有才商品CODE' => 'product_code',
                '金蝶客户编码' => 'jdy_num',

            ];


            $insert = [];
            // Db::startTrans();
            try {
                $api = new Jdy();

                if (!$PHPExcel = $reader->load($filePath)) {
                    $this->error(__('Unknown data format'));
                }
                $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
                $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                $fields = [];
                for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $fields[] = $val;
                    }
                }

                $i = 1;
                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getFormattedValue();
                        $values[] = is_null($val) ? '' : $val;
                    }
                    $row = [];
                    $temp = array_combine($fields, $values);

                    foreach ($temp as $k => $v) {
                        // var_dump($k);var_dump($v);die;
                        if (isset($fieldArr[$k]) && $k !== '') {
                            // ltrim($v,'`');
                            $row[$fieldArr[$k]] = ltrim($v, '`');
                        }
                    }
                    if ($row) {

                        // $row['admin_id'] = $pg['admin_id'];
                        // $row['kl_num'] = $row['kl_num'] ?? $row['out_num'];
                        // $row['pg_id'] = $ids;
                        // $row['no'] = $row['no'] ?? $row['s_no'];
                        // $row['c_no'] = date('Ymd') . $row['no'];
                        // $row['c_no'] = date('Ymd').'-'.$ids.'-'.($currentRow-1).'-'.$row['no'];
                        // $row['true_el'] = floatval($row['true_el'] ?? 0);
                        // $row['top_el']  = floatval($row['top_el'] ?? 0);
                        // $row['normal_el'] = floatval($row['normal_el'] ?? 0);
                        // $row['low_el'] = floatval($row['low_el'] ?? 0);
                        if ($row['id'] && $row['jdy_num']) {
                            $has = ModelCustom::get($row['id']);
                            if ($has && (!$has->jdy_id || $has->jdy_num != $row['jdy_num'])) {
                                $id = $api->getCustom($row['jdy_num']);
                                if ($id) {
                                    $has->jdy_num = $row['jdy_num'];
                                    $has->jdy_id = $id;
                                    $has->save();
                                }
                            }
                        }
                    }
                }

                // $this->model->saveAll($insert);


                // Db::commit();
            } catch (PDOException $e) {
                // Db::rollback();
                // dump($e);
                $this->error('操作失败:异常' . $e->getMessage() . '');
                // Db::commit();

            } catch (Exception $e) {
                // dump($e);

                // dump($e->getMessage());
                // dump($e->getLine());
                // dump($e->getFile());


                // Db::rollback();
                $this->error($e->getMessage());
            }
            if ($msg) {
                $this->error($msg);
            }



            //删除导入文件
            @unlink($filePath);
            $this->success();
        }

        return $this->view->fetch();
    }
}
